import { createApp } from "vue";
import App from "./App.vue";
import store from "./store";
import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import MicroAppAction, { Actions } from "@/utils/microAppAction";
import InitRouter from "@/router/initRouter";
import { formatMicroRoute } from "@/utils/common";
import { addAsyncRoute } from "@/router/utils";
let router = null;
let app: any = null;

// 渲染
const render = (props: Actions): void => {
  const { container, asyncRoutes, mainRouter } = props;
  app = createApp(App);
  MicroAppAction.setActions(props);
  let routes = [];
  // 作为微应用运行时，路由通过主应用传递获取
  if (window.__POWERED_BY_QIANKUN__) {
    routes = asyncRoutes.map((t: RouteRecordRaw) => {
      return {
        ...t,
        path: formatMicroRoute(t.path) // 主应用传递过来的路由都会带上子应用的前缀、但是对于子应用router来说运行时是默认带 /app-vue/前缀的，所以这里需要将主应用中的前缀去掉
      };
    });
    app.config.globalProperties.$mainRouter = mainRouter;
    // 工程化引入组件
    addAsyncRoute(routes);
  }
  router = createRouter({
    history: createWebHistory(window.__POWERED_BY_QIANKUN__ ? "/app-vue/" : "/"),
    routes: routes || []
  });
  // 初始化路由守卫
  InitRouter(router);
  app
    .use(store)
    .use(router)
    .mount(container ? container.querySelector("#app") : "#app");
};
// 此处使用断言、解决ts类型检验window上不存在__POWERED_BY_QIANKUN__属性的错误
if (!window.__POWERED_BY_QIANKUN__) {
  render({} as Actions);
}

// 导出qiankun的几个生命周期函数
export async function bootstrap() {
  console.log("bootstrap");
}

export async function mount(props: Actions) {
  // 接受到主应用传递过来的数据信息
  // 注意：props需要含有container属性、用于防止多应用绑定同一个根节点问题
  render(props);
}
export async function unmount() {
  console.log("微应用卸载");
  router = null;
  app && (app = null);
}
